package com.smzd.ccms.actions;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.smzd.ccms.business.ArticleService;
import com.smzd.ccms.business.AttachmentService;
import com.smzd.ccms.domain.Article;
import com.smzd.ccms.domain.Attachment;
import com.smzd.ccms.domain.Site;
import com.smzd.framework.annotation.Access;
import com.smzd.framework.core.actions.AbstractScopedController;
import com.smzd.framework.core.business.IFGService;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.db.SRPage;
import com.smzd.utils.SessionHolder;

@Controller
@RequestMapping("/article/{articleId}/attachments")
@Access("TAG_ROLE_CCMS")
public class AttachmentController extends AbstractScopedController<Attachment, Article> {
	private static final String NO_CALLBACK = "_no_cb_";
	public static File UPLOAD_ROOT;
	@Autowired
	private AttachmentService service;
	@Autowired
	private ArticleService articleservice;

	@Override
	protected IFGService<Attachment> getService() {
		return service;
	}

	@Override
	protected Article getScope(int scopeId) {
		return new Article(scopeId);
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	@Override
	public String toAddPage(Map<String, Object> model, @PathVariable("articleId") int scopeId, Attachment elem,
	        BindingResult result) throws Exception {
		model.put("id", scopeId);
		return super.toAddPage(model, scopeId, elem, result);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postAddData(Map<String, Object> model, @PathVariable("articleId") int scopeId, Attachment elem,
	        BindingResult result) throws Exception {
		model.put("id", scopeId);
		return super.postAddData(model, scopeId, elem, result);
	}

	@RequestMapping(value = { "", "/index.html" }, method = RequestMethod.GET)
	@Override
	public String toListPage(Map<String, Object> model, @PathVariable("articleId") int scopeId, Attachment elem,
	        BindingResult result) throws Exception {
		model.put("id", scopeId);
		return super.toListPage(model, scopeId, elem, result);
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String getListData(Map<String, Object> model, @PathVariable("articleId") int scopeId,
	        SRPage<Article, Attachment> page, BindingResult result) throws Exception {
		model.put("id", scopeId);
		return super.getListData(model, scopeId, page, result);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	@Override
	public String toEditPage(Map<String, Object> model, @PathVariable("articleId") int scopeId, Attachment elem,
	        BindingResult result) throws Exception {
		model.put("id", scopeId);
		System.out.println("测试");
		elem = service.getItemById(elem.getId());
		return super.toEditPage(model, scopeId, elem, result);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postEditData(Map<String, Object> model, @PathVariable("articleId") int scopeId, Attachment elem,
	        BindingResult result) throws Exception {
		model.put("id", scopeId);
		return super.postEditData(model, scopeId, elem, result);
	}

	@RequestMapping(value = "/remove", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postRemoveData(Map<String, Object> model, @PathVariable("articleId") int scopeId, Attachment elem,
	        BindingResult result) throws Exception {
		model.put("id", scopeId);
		return super.postRemoveData(model, scopeId, elem, result);
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String fileUpload(Map<String, Object> model,
	        @RequestParam(value = "callback", required = false, defaultValue = NO_CALLBACK) String callback,
	        @RequestParam(value = "meta", required = false) String meta,
	        @RequestParam(value = "name", required = true) String name,
	        @RequestParam(value = "desc", required = false, defaultValue = "") String description,
	        @PathVariable("articleId") int scopeId,
	        HttpServletRequest request, @RequestParam(value = "file") MultipartFile multipartFile) {
		Map<String, Object> root = new HashMap<String, Object>();
		if (callback != null && callback.length() > 0 && !callback.equals(NO_CALLBACK)) {
			root.put("callback", callback);
			model.put("callback", callback);
		}
		root.put("meta", meta);
		String page = "uploadcomplete.ftl";// 你需要一个页面来执行一段js
		if (multipartFile == null) {
			root.put("err", "没有上传文件！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		String origin = multipartFile.getOriginalFilename();
		root.put("origin", origin);
		long size = multipartFile.getSize();
		root.put("size", size);
		System.out.println("----------文件上传，文件大小是" + size);
		if (multipartFile.getSize() > 51200000) {
			root.put("err", "图片大于500M！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		int idx = origin.lastIndexOf(".");
		if (idx < 0) {
			root.put("err", "文件格式不正确！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		String ext = origin.substring(idx);
		if (ext.trim().length() == 0) {
			root.put("err", "文件格式不正确！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		if (!checkFileExt(ext)) {
			root.put("err", "文件格式不正确！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		root.put("ext", ext);

		String filename = UUID.randomUUID().toString() + ext;
		root.put("name", filename);
		System.out.println("----------文件上传，生成的随机文件名是" + filename);
		root.put("path", "/files");

		if (UPLOAD_ROOT == null) {
			ServletContext context = request.getSession().getServletContext();
			File uploadPath = new File(context.getRealPath("/files"));
			uploadPath.mkdirs();
			UPLOAD_ROOT = uploadPath;
		}
		Site site = SessionHolder.getObject(Site.SESSION_KEY_CURRENT_SITE);
		File dir = new File(UPLOAD_ROOT, site.getPath());
		dir.mkdirs();
		try {
			multipartFile.transferTo(new File(dir, filename));
		} catch (Exception e) {
			e.printStackTrace();
			model.put("json", JsonHelper.getFailJsonString("文件上传失败！"));
			return getMyView(page);
		}
		root.put("msg", "文件上传成功！");
		Attachment attachment = new Attachment();
		Article article = new Article(scopeId);
		attachment.setScope(article);
		attachment.setName(name);
		attachment.setDescription(description);
		attachment.setPath(filename);
		attachment.setType(0);
		service.insert(attachment);
		root.put("id", attachment.getId());
		model.put("json", JsonHelper.getSuccessJsonString(root));
		return "fileupload/" + page;
	}

	private boolean checkFileExt(String ext) {
		return true;
	}
}